package com.mrx.xfriendship.telnet.server;

import com.mrx.xfriendship.telnet.command.AbstractCommand;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Mr.X
 * @since 2023-01-23 11:46
 */
public class TelnetServer {


    @Resource
    private List<AbstractCommand> commandList;

    private static final Logger logger = LoggerFactory.getLogger(TelnetServer.class);

    @Async
    public void startServer() throws Exception {
        logger.debug("正在启动 Telnet 服务器");
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new TelnetServerInitializer(new TelnetServerHandler(this::userHandler, commandList)));
            b.bind(23).sync().channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    private boolean userHandler(String name, String pass) {
        return "admin".equals(name) && "admin".equals(pass) || "test".equals(name) && "test".equals(pass);
    }

}
